package lt.ntec.danblog.server.core.model.gae;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import lt.ntec.danblog.server.core.UserNotFoundException;
import lt.ntec.danblog.server.core.model.User;
import lt.ntec.danblog.server.core.model.UserDAO;
import com.google.inject.Inject;

class JDOUserDAO extends JDOBaseDAO<User> implements UserDAO {

    @Inject
    public JDOUserDAO(PersistenceManager pm) {
        super(pm);
    }

    @SuppressWarnings("unchecked")
    @Override
    public User getUserByEmail(String email) throws UserNotFoundException {
        Query query = pm.newQuery(JDOUser.class, "email == emailParam");
        List<JDOUser> results;
        try {
            query.declareParameters("String emailParam");
            results = (List<JDOUser>) query.execute(email);
            if (results.isEmpty()) {
                throw new UserNotFoundException("No such user exists");
            }
        } finally {
            query.closeAll();
        }
        return results.get(0);
    }

    @Override
    public Class<? extends User> getEntityClass() {
        return JDOUser.class;
    }
}
